package com.project.lk.nurseapp.login.model;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.reflect.TypeToken;
import com.project.lk.nurseapp.base.BaseApi;
import com.project.lk.nurseapp.base.PostBaseModel;
import com.project.lk.nurseapp.utils.JsonUtils;
import com.project.lk.nurseapp.utils.MD5;
import com.project.lk.nurseapp.utils.ToastUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.FormBody;

/**
 * 功能介绍：
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class LoginModel extends PostBaseModel {


    public void postLoadJson(String url,String phone,String psw,String logintype,String openid,String nickname,String headimg) {
        FormBody.Builder builder=new FormBody.Builder();
        Random random = new Random();
        int nextInt = random.nextInt();
        long currentTimeMillis = System.currentTimeMillis();
        builder.add("signature",postSignToken(currentTimeMillis+"",nextInt+""))
                .add("timestamp",currentTimeMillis+"")
                .add("nonce",nextInt+"");
        if (TextUtils.equals(logintype,"0")){
            builder.add("username",phone)
                    .add("password", MD5.getStringMD5(psw+ BaseApi.token));
        }else {
            builder.add("openid",openid)
                    .add("nickname",nickname)
                    .add(headimg,"headimg");
        }
        getJsonData(url,builder.build());

    }



    @Override
    public List analyzeJson(String json, String url) {  //解析json
        Log.e("MLOG",url+json);
        try {
            JSONObject jsonObject=new JSONObject(json);
            String msg = jsonObject.getString("msg");
            String info = jsonObject.getString("info");
            ToastUtils.showShortToast(info);//显示提示信息
            if (TextUtils.equals(msg,"success")){
                JSONObject data = jsonObject.getJSONObject("data");
                List<UserBean> list=new ArrayList<>();
                UserBean bean = (UserBean) JsonUtils.getJsonUtils()
                        .toObject(new TypeToken<UserBean>() {
                        }.getType(), data.toString());
                list.add(bean);
                loginSuccess(list);
                return list;
            }else {
                loginFail();
            }
          return null;
        } catch (Exception e) {
            e.printStackTrace();
            loginFail();
//            Log.e("MLOG",e.getMessage());
        }
        return null;
    }



    @Override
    public void postSuccessOnMainThread(List list, String url) {
        //请求成功
    }
    //登录成功
    public void loginSuccess(List<UserBean> list){

        bridge.bridge(BaseApi.login_success,list);
    }
    //登录失败
    public void loginFail(){
        bridge.bridge(BaseApi.login_fail,null);
    }

    @Override
    public void postFailedOnMainThread(String url) {

            loginFail();
    }




}
